package com.mallcai.bigdata.ladon.service.report.impl;

import com.cake.bigdata.starter.exception.category.BusinessException;
import com.mallcai.bigdata.ladon.client.vo.ReportColumnVO;
import com.mallcai.bigdata.ladon.client.vo.ReportDataVO;
import com.mallcai.bigdata.ladon.datasource.ResultSetDataTool;
import com.mallcai.bigdata.ladon.dpl.vo.DataType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.ResultSetExtractor;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-24 17:51
 */
@Slf4j
public class ReportDataVoExtractor implements ResultSetExtractor<ReportDataVO> {


    @Override
    public ReportDataVO extractData(ResultSet resultSet) {
        try{
            //获取列表对象
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            String column;
            //获取查询结果字段信息
            final int size = resultSetMetaData.getColumnCount();
            List<ReportColumnVO> columns = new ArrayList<>();
            Map<String, DataType> columnTypes = new HashMap<>();
            for (int i = 1; i <= size; i++) {
                column = resultSetMetaData.getColumnLabel(i);
                DataType type = ResultSetDataTool.getDataType(resultSetMetaData.getColumnClassName(i));
                columnTypes.put(column, type);
                columns.add(createReportColumnVO(column, type));
            }

            //获取结果集
            Object columnValue;
            List<Map<String, Object>> rows = new ArrayList<>();
            while (resultSet.next()) {
                Map<String, Object> row = new HashMap<>();
                for (int i = 1; i <= size; i++) {
                    column = resultSetMetaData.getColumnLabel(i);
                    DataType dt = columnTypes.get(column);
                    if (dt == null) {
                        continue;
                    }
                    columnValue = ResultSetDataTool.getValue(resultSet, column, dt);
                    row.put(column, columnValue);
                }
                rows.add(row);
            }
            log.debug("查询结果: 数据{}条", rows.size());
            return new ReportDataVO(columns, rows);
        }catch (Exception e){
            throw new BusinessException(e);
        }
    }

    private ReportColumnVO createReportColumnVO(String column, DataType dataType){
       ReportColumnVO reportColumnVO =  new ReportColumnVO();
       reportColumnVO.setDataType(dataType.getCode());
       reportColumnVO.setName(column);
       reportColumnVO.setShowName(column);
       return reportColumnVO;
    }


}
